import 'package:cgvc/basis/basis_view_model.dart';
import 'package:cgvc/helper/string_helper.dart';
import 'package:cgvc/model/app_update_model.dart';
import 'package:cgvc/util/dialog_util.dart';
import 'package:cgvc/util/platform_util.dart';
import 'package:cgvc/util/toast_util.dart';
import 'package:cgvc/view_model/theme_view_model.dart';
import 'package:flutter/cupertino.dart';
import 'package:cgvc/data/update_repository.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

class UpdateViewModel extends BasisViewModel {
  static String _appVersion;

  static String get appVersion => _appVersion;

  static String _appVersionCode;

  static String get appVersionCode =>
      _appVersionCode != null ? _appVersionCode : '-1';

  UpdateViewModel() {
    PlatformUtil.getAppVersion().then((value) {
      _appVersion = value;
      setSuccess();
    });
    PlatformUtil.getBuildNumber().then((value) {
      _appVersionCode = value;
      setSuccess();
    });
  }

  Future<AppUpdateModel> checkUpdate(BuildContext context,
      {bool showError = false}) async {
    AppUpdateModel appModel;
    setLoading();
    try {
      appModel = await UpdateRepository.checkUpdate();
      showUpdateDialog(context, appModel, backgroud: !showError);
      setSuccess();
    } catch (e, s) {
      setError(e, s);
      if (showError) {
        ToastUtil.show('检查失败，请稍后重试!$e', duration: Duration(seconds: 6));
      }
    }

    return appModel;
  }

  Future<void> showUpdateDialog(BuildContext context, AppUpdateModel info,
      {bool backgroud = true}) async {
    //判断是否需要弹框
    if (info == null || !info.buildHaveNewVersion) {
      if (!backgroud) {
        ToastUtil.show(StringHelper.getS().currentIsNew);
      }
      return;
    }

    int index = await DialogUtil.showAlertDialog(context,
        titleWidget: RichText(
          textScaleFactor: ThemeViewModel.textScaleFactor,
          text: TextSpan(
            style: Theme.of(context).textTheme.subtitle1,
            text: '发现新版本:${info.buildVersion}',
            children: [
              TextSpan(
                style: Theme.of(context).textTheme.subtitle1.copyWith(
                      fontSize: 13,
                      color: Theme.of(context).accentColor,
                    ),
                text: '\n系统自带浏览器打开',
              )
            ],
          ),
        ),
        content: info.buildUpdateDescription,
        cancel: StringHelper.getS().updateNextTime,
        ensure: StringHelper.getS().updateNow);
    if (index == 1) {
      launch(info.downloadURL);
    }
  }
}
